const workRecord = require('../models/workRecords')

var express = require('express');
var router = express.Router();

var formidable = require('formidable');

router.post('/', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async (err, fields) => {
        if(err) {
            res.json({'state': false, 'msg': err});
        }else {
            var formatDate = function (date) {
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h=h < 10 ? ('0' + h) : h;
                var minute = date.getMinutes();
                minute = minute < 10 ? ('0' + minute) : minute;
                var second=date.getSeconds();
                second=second < 10 ? ('0' + second) : second;
                return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
            }

            var user_num = function(time_s, time_e) {
                return new Promise((resolve, reject) => {
                    workRecord.find({
                        time: {
                            $gte: time_s,
                            $lte: time_e
                        }
                    }).distinct("UUID",(err, results) => {
                        if(err) {
                            res.json({'state': false, 'msg': err});
                        }else {
                            resolve(results.length);
                        }
                    })
                })
            }
            var time_s = new Date(new Date(fields.time).setDate(1));
            time_s.setHours(0);
            time_s.setMinutes(0);
            time_s.setSeconds(0);
            time_s.setMilliseconds(0);
            time_s = new Date(time_s);
            var time_e = new Date(time_s);
            time_e.setMonth(time_e.getMonth()+1);
            var num = Math.round((time_e-time_s)/(24*60*60*1000));
            var time_interval = [formatDate(new Date(new Date(time_s)+(8*60*60*1000)))];
            for(let i=0;i<num;i++) {
                var time_t = new Date(time_s.setDate(time_s.getDate()+1))
                time_interval.push(formatDate(new Date(new Date(time_t)+(8*60*60*1000))));
            }
            // console.log(time_interval);
            var numByDay = [];
            for(let j=1;j<time_interval.length;j++) {
                let num = await user_num(time_interval[j-1], time_interval[j]);
                let data = {
                    "time": j,
                    "num": num
                }
                numByDay.push(data);
            }
            res.json({
                'state': true,
                'month': `${new Date(fields.time).getFullYear()}年${new Date(fields.time).getMonth()+1}月`,
                'numByDay': numByDay
            });
        }
    });
})

module.exports = router;